
let listenerID = 0
class EventEmitter {
    public _events: any
    constructor() {
        this._events = {}
    }

    emit(type: string, data?: any) {
        let listeners = this._events[type]
        if (listeners) {
            for (let listener of listeners) {
                listener[0](data)
            }
        }
    }

    on(type: string, listener): number {
        if (!this._events[type]) {
            this._events[type] = []
        }
        listenerID += 1
        this._events[type].push([listener, listenerID])
        return listenerID
    }
    removeListener(type, listenerID: number) {
        let listeners = this._events[type]
        if (listeners) {
            for (let i = 0; i < listeners.length; i++) {
                if (listeners[i][1] === listenerID) {
                    listeners.splice(i, 1)
                    break
                }
            }
            if (listeners.length === 0) {
                this._events[type] = null
            }
        }
    }
    removeAllListeners(type: string) {
        this._events[type] = null
    }
    listeners(type: string) {
        return this._events[type]
    }
}
let eventEmitter = new EventEmitter()
export default eventEmitter